from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import json
import os
from datetime import datetime

app = Flask(__name__, static_folder='.')
CORS(app)  # 允许跨域请求

# 数据文件路径
DATA_FILE = 'account_data.json'
CONFIG_FILE = 'config.json'

def load_data():
    """从JSON文件加载台账数据"""
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                data = json.load(f)
                print(f"成功加载 {len(data)} 条记录")
                return data
        except Exception as e:
            print(f"加载数据失败: {str(e)}")
            return []
    print("数据文件不存在，返回空数组")
    return []

def save_data(data):
    """将台账数据保存到JSON文件"""
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        print(f"成功保存 {len(data)} 条记录")
        return True
    except Exception as e:
        print(f"保存数据失败: {str(e)}")
        return False

def load_config():
    """从JSON文件加载配置数据"""
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                config = json.load(f)
                print("成功加载配置")
                return config
        except Exception as e:
            print(f"加载配置失败: {str(e)}")
            return {}
    print("配置文件不存在，返回空字典")
    return {}

def save_config(config):
    """将配置数据保存到JSON文件"""
    try:
        with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=4)
        print("成功保存配置")
        return True
    except Exception as e:
        print(f"保存配置失败: {str(e)}")
        return False

@app.route('/')
def index():
    return send_from_directory('.', 'index.html')

# 添加静态文件路由
@app.route('/<path:filename>')
def serve_static(filename):
    return send_from_directory('.', filename)

@app.route('/api/accounts', methods=['GET'])
def get_accounts():
    """获取所有台账记录"""
    try:
        accounts = load_data()
        return jsonify({'success': True, 'data': accounts})
    except Exception as e:
        print(f"获取台账记录失败: {str(e)}")
        return jsonify({'success': False, 'error': str(e)})

@app.route('/api/accounts', methods=['POST'])
def save_accounts():
    """保存台账记录"""
    try:
        data = request.json.get('data')
        print(f"接收到 {len(data) if data else 0} 条记录用于保存")
        if save_data(data):
            return jsonify({'success': True})
        else:
            return jsonify({'success': False, 'error': '保存失败'})
    except Exception as e:
        print(f"保存台账记录失败: {str(e)}")
        return jsonify({'success': False, 'error': str(e)})

@app.route('/api/config', methods=['GET'])
def get_config():
    """获取配置信息"""
    try:
        config = load_config()
        return jsonify({'success': True, 'data': config})
    except Exception as e:
        print(f"获取配置失败: {str(e)}")
        return jsonify({'success': False, 'error': str(e)})

@app.route('/api/config', methods=['POST'])
def save_config_api():
    """保存配置信息"""
    try:
        config = request.json.get('data')
        print(f"接收到配置数据: {config}")
        if save_config(config):
            return jsonify({'success': True})
        else:
            return jsonify({'success': False, 'error': '保存失败'})
    except Exception as e:
        print(f"保存配置失败: {str(e)}")
        return jsonify({'success': False, 'error': str(e)})

if __name__ == '__main__':
    app.run(host='localhost', port=5000, debug=True)